package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.IpUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.WebUser;
import com.ruoyi.system.domain.WebUserAccount;
import com.ruoyi.system.domain.WebUserRecommendAward;
import com.ruoyi.system.mapper.WebUserMapper;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.IWebUserAccountService;
import com.ruoyi.system.service.IWebUserRecommendAwardService;
import com.ruoyi.system.service.IWebUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户Service业务层处理
 * 
 * @author ruoyi
 * @date 2021-05-22
 */
@Service
public class WebUserServiceImpl extends ServiceImpl<WebUserMapper, WebUser> implements IWebUserService
{
    @Autowired
    private WebUserMapper webUserMapper;
    @Autowired
    private IWebUserAccountService iWebUserAccountService;
    @Autowired
    private IWebUserRecommendAwardService iWebUserRecommendAwardService;
    @Autowired
    private ISysConfigService configService;

    /**
     * 查询用户
     * 
     * @param id 用户ID
     * @return 用户
     */
    @Override
    public WebUser selectWebUserById(Long id)
    {
        return webUserMapper.selectWebUserById(id);
    }

    /**
     * 查询用户列表
     * 
     * @param webUser 用户
     * @return 用户
     */
    @Override
    @DataScope(deptAlias = "t1")
    public List<WebUser> selectWebUserList(WebUser webUser)
    {
        return webUserMapper.selectWebUserList(webUser);
    }

    /**
     * 新增用户
     * 
     * @param webUser 用户
     * @return 结果
     */
    @Override
    public int insertWebUser(WebUser webUser)
    {
        webUser.setCreateTime(DateUtils.getNowDate());
        return webUserMapper.insertWebUser(webUser);
    }

    @Override
    @Transactional
    public Map<String, Object> saveRegisterUser(String nickName, String headPic , String recommendCode , String wxOpenid, HttpServletRequest request){
        WebUser userData = getOne(new QueryWrapper<WebUser>().eq("wx_open_id", wxOpenid));
        //没有找到这个用户
        if (userData == null) {
            userData = new WebUser();
            userData.setUserType("1"); //普通会员
            userData.setSourceType(2L); //微信注册
            userData.setRealAuth(0); //未实名认证
            userData.setStatus(0L); //正常
            userData.setWxOpenId(wxOpenid);
            userData.setNickname(nickName);
            userData.setHeadPic(headPic);
            userData.setRecommCode(StringUtils.Rc4StringNo());
            userData.setLastLoginDate(DateUtils.getNowDate());
            userData.setLastLoginIp(IpUtils.getIpAddr(request));
            this.save(userData);

            if(StringUtils.isNotEmpty(recommendCode)){
                //推荐人
                WebUser recommendUser = getOne(new QueryWrapper<WebUser>().eq("recomm_code", recommendCode));
                if(recommendUser != null){
                    userData.setParentId(recommendUser.getId()+"");
                    userData.setParentTime(DateUtils.getNowDate());

                    Long score_proportion = Long.valueOf(configService.selectConfigByKey("score_proportion"));
                    if(score_proportion != null){
                        WebUserRecommendAward recommendAward = new WebUserRecommendAward();
                        recommendAward.setUserId(recommendUser.getId());
                        recommendAward.setRecommendUser(userData.getId());
                        recommendAward.setAmout(score_proportion);
                        recommendAward.setCurrentTotal(userData.getScore());
                        recommendAward.setType(1L);
                        iWebUserRecommendAwardService.save(recommendAward);
                    }

                    recommendUser.setScore(Integer.valueOf(recommendUser.getScore()+score_proportion+""));
                    this.saveOrUpdate(recommendUser);

                }
            }
        } else {
            if(userData.getStatus() == 1){
                throw new BusinessException("当前用户已被禁止登录");
            }
            //存在用户更新头像与昵称
            WebUser userUp = new WebUser();
            userUp.setNickname(nickName);
            userUp.setHeadPic(headPic);
            userUp.setLastLoginDate(DateUtils.getNowDate());
            userUp.setLastLoginIp(IpUtils.getIpAddr(request));
            this.update(userUp, new UpdateWrapper<WebUser>().eq("id", userData.getId()));
        }

        Map<String, Object> map = new HashMap<>();
        map.put("openId", userData.getWxOpenId());
        map.put("userId", userData.getId());
        map.put("heandImg", userData.getHeadPic());
        map.put("mobile", userData.getMobile());
        return map;
    }

    /**
     * 修改用户
     * 
     * @param webUser 用户
     * @return 结果
     */
    @Override
    public boolean updateWebUser(WebUser webUser , WebUserAccount account)
    {
        //webUser.setUpdateTime(DateUtils.getNowDate());
        //return webUserMapper.updateWebUser(webUser);
        if(account != null){
            WebUserAccount dataAccount = iWebUserAccountService.getOne(new QueryWrapper<WebUserAccount>().eq("user_id",webUser.getId()));
            if(dataAccount != null){
                if(StringUtils.isNotEmpty(account.getIdcard())){
                    dataAccount.setIdcard(account.getIdcard());
                }
                if(StringUtils.isNotEmpty(account.getIdCardA())){
                    dataAccount.setIdCardA(account.getIdCardA());
                }
                if(StringUtils.isNotEmpty(account.getIdCardB())){
                    dataAccount.setIdCardB(account.getIdCardB());
                }
                if(account.getBindType() != null){
                    dataAccount.setBindType(account.getBindType());
                }
                if(StringUtils.isNotEmpty(account.getBankType())){
                    dataAccount.setBankType(account.getBankType());
                }
                if(StringUtils.isNotEmpty(account.getAlipayNo())){
                    dataAccount.setAlipayNo(account.getAlipayNo());
                }
                if(StringUtils.isNotEmpty(account.getBankNo())){
                    dataAccount.setBankNo(account.getBankNo());
                }
                this.iWebUserAccountService.updateById(dataAccount);
            }

        }
        return this.saveOrUpdate(webUser);
    }

    /**
     * 删除用户对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public boolean deleteWebUserByIds(String ids)
    {
        //return webUserMapper.deleteWebUserByIds(Convert.toStrArray(ids));
        return this.removeByIds(Arrays.asList(Convert.toStrArray(ids)));
    }

    /**
     * 删除用户信息
     * 
     * @param id 用户ID
     * @return 结果
     */
    @Override
    public boolean deleteWebUserById(Long id)
    {
        //return webUserMapper.deleteWebUserById(id);
        return this.removeById(id);
    }

    @Override
    @DataScope(deptAlias = "t1")
    public Map<String,Object> selectIndexUserData1(WebUser webUser){
        return this.webUserMapper.selectIndexUserData1(webUser);
    }
    @Override
    @DataScope(deptAlias = "t1")
    public Map<String,Object> selectIndexUserData2(WebUser webUser){
        return this.webUserMapper.selectIndexUserData2(webUser);
    }
    @Override
    @DataScope(deptAlias = "t1")
    public Map<String,Object> selectIndexUserData3(WebUser webUser){
        return this.webUserMapper.selectIndexUserData3(webUser);
    }
    @Override
    @DataScope(deptAlias = "t1")
    public Map<String,Object> selectIndexUserData4(WebUser webUser){
        return this.webUserMapper.selectIndexUserData4(webUser);
    }

    /**
     * 服务人员对应的服务项目统计
     * @param webUser
     * @return
     */
    @Override
    @DataScope(deptAlias = "b")
    public List<Map> selStatistics(WebUser webUser){
        return this.webUserMapper.selStatistics(webUser);
    }

    /**
     * 查看详情
     * @param webUser
     * @return
     */
    @Override
    @DataScope(deptAlias = "b")
    public List<Map> selStatisticsDetaiList(WebUser webUser){
        return this.webUserMapper.selStatisticsDetaiList(webUser);
    }

    /**
     * 服务人员对应的服务项目统计
     * @param webUser
     * @return
     */
    @Override
    @DataScope(deptAlias = "b")
    public List<Map> selStatistics2(WebUser webUser){
        return this.webUserMapper.selStatistics2(webUser);
    }

    /**
     * 服务人员对应的服务项目统计
     * @param webUser
     * @return
     */
    @Override
    @DataScope(deptAlias = "b")
    public List<Map> selStatistics2DetailList(WebUser webUser){
        return this.webUserMapper.selStatistics2DetailList(webUser);
    }

    /**
     * 服务人员对应的服务项目统计
     * @param webUser
     * @return
     */
    @Override
    @DataScope(deptAlias = "a")
    public List<Map> selStatistics3(WebUser webUser){
        return this.webUserMapper.selStatistics3(webUser);
    }

    /**
     * 服务人员对应的服务项目统计列表
     * @param webUser
     * @return
     */
    @Override
    @DataScope(deptAlias = "a")
    public List<Map> selStatistics3DetailList(WebUser webUser){
        return this.webUserMapper.selStatistics3DetailList(webUser);
    }

    /**
     * 服务人员对应的服务项目统计
     * @param webUser
     * @return
     */
    @Override
    @DataScope(deptAlias = "c")
    public List<Map> selStatistics4(WebUser webUser){
        return this.webUserMapper.selStatistics4(webUser);
    }
}
